<template>
  <h-drawer
    v-model="visible"
    title="工单费用详情"
    :loading="getOrderFeeDetailProjectLoading || loading"
    :width="80"
    @close="onClose"
  >
    <div class="detail_info_container">
      <div class="title">基本信息</div>
      <div v-if="detailData" class="detail_info">
        <div class="info_item_container">
          <div class="info_item">
            <div class="label">费用单号:</div>
            <div class="value">{{ detailData.feeNo }}</div>
          </div>
          <div class="info_item">
            <div class="label">关联工单:</div>
            <div class="value">{{ detailData.workNo }}</div>
          </div>
          <div class="info_item">
            <div class="label">费用状态:</div>
            <div class="value">
              <h-status v-if="detailData.status === 1" type="warning">待审核</h-status>
              <h-status v-if="detailData.status === 2" type="success">已通过</h-status>
              <h-status v-if="detailData.status === 3" type="error">已驳回</h-status>
              <h-status v-if="detailData.status === 4" type="info">已撤回</h-status>
              <h-status v-if="detailData.status === 5" type="info">已取消</h-status>
            </div>
          </div>
          <div class="info_item">
            <div class="label">结算类型:</div>
            <div class="value">{{ detailData.settlementType }}</div>
          </div>
          <div class="info_item">
            <div class="label">申请人员:</div>
            <div class="value">{{ detailData.applyEmp }}</div>
          </div>
        </div>
        <div class="info_item_container">
          <div class="info_item">
            <div class="label">申请时间:</div>
            <div class="value">{{ detailData.createTime }}</div>
          </div>
          <div class="info_item">
            <div class="label">审批时间:</div>
            <div class="value">{{ detailData.reviewTime }}</div>
          </div>
          <div class="info_item">
            <div class="label">审批人员:</div>
            <div class="value">{{ detailData.reviewEmp }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="body">
      <el-tabs v-model="activeName" class="table-detail" @tab-change="handleClick">
        <!-- 费用项目 -->
        <el-tab-pane label="费用项目" name="first">
          <div class="fee_project">
            <el-table :border="true" stripe resizable height="100%" :data="feeDetails">
              <template #empty>
                <el-empty description="暂无数据" :image-size="60" />
              </template>

              <!-- 序号 -->
              <el-table-column
                label="序号"
                fixed="left"
                width="50"
                :align="'center'"
                type="index"
              />

              <!-- 审核状态 -->
              <el-table-column
                prop="name"
                label="审核状态"
                width="90"
                fixed="right"
                :align="'center'"
              >
                <template #default="{ row }">
                  <div class="flex_justify_center">
                    <h-status v-if="row.status === 1" type="warning">待审核</h-status>
                    <h-status v-else-if="row.status === 2" type="success">已通过</h-status>
                    <h-status v-else type="error">已驳回</h-status>
                  </div>
                </template>
              </el-table-column>

              <!--收支类型-->
              <el-table-column label="收支类型" prop="date" show-overflow-tooltip width="100">
                <template #default="{ row }">
                  <span v-if="row.type === 1">厂家承担</span>
                  <span v-else-if="row.type === 2">收取公司</span>
                  <span v-else-if="row.type === 3">支付部门</span>
                </template>
              </el-table-column>

              <!-- 费用名称 -->
              <el-table-column show-overflow-tooltip prop="name" label="费用名称" width="100" />

              <!-- 公里数 -->
              <!-- <el-table-column show-overflow-tooltip prop="kilometers" label="公里数" width="100" /> -->

              <!-- 数量 -->
              <el-table-column show-overflow-tooltip prop="qty" label="数量" width="80" />

              <!-- 平台承担总费用 -->
              <el-table-column
                show-overflow-tooltip
                prop="price"
                label="厂家承担总费用"
                width="150"
              >
                <template #default="{ row }"> ￥{{ (row.price || 0).toFixed(2) }} </template>
              </el-table-column>

              <!-- 收取公司总费用 -->
              <el-table-column
                show-overflow-tooltip
                prop="customerUndertakePrice"
                label="收取公司总费用"
                width="150"
              >
                <template #default="{ row }">
                  ￥{{ (row.customerUndertakePrice || 0).toFixed(2) }}
                </template>
              </el-table-column>
              <!-- 支付部门总费用 -->
              <el-table-column
                show-overflow-tooltip
                prop="networkUndertakePrice"
                label="支付部门总费用"
                width="150"
              >
                <template #default="{ row }">
                  ￥{{ (row.networkUndertakePrice || 0).toFixed(2) }}
                </template>
              </el-table-column>

              <!-- 备注 -->
              <el-table-column show-overflow-tooltip prop="remark" label="备注" width="170" />

              <!-- 附件 -->
              <el-table-column prop="city" label="附件" :width="annexColumnWidth">
                <template #default="{ row }">
                  <div style="display: flex; align-items: center; gap: 8px">
                    <div v-for="(img, imgIndex) in row.images" :key="img.id">
                      <h-image
                        :width="60"
                        :height="40"
                        :src="img.image"
                        :preview-src-list="row.images.map((item) => item.image)"
                        :initial-index="imgIndex"
                        fit="contain"
                        :padding="2"
                        :show-del-btn="false"
                      />
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 操作日志 -->
        <el-tab-pane label="操作日志" name="third">
          <div class="operate_log_container">
            <div class="table">
              <el-table :border="true" stripe resizable height="100%" :data="detailDataLog">
                <template #empty>
                  <el-empty description="暂无数据" :image-size="60" />
                </template>
                <el-table-column
                  label="序号"
                  fixed="left"
                  width="50"
                  :align="'center'"
                  type="index"
                />
                <el-table-column show-overflow-tooltip prop="state" label="操作人" width="140">
                  <template #default="i">
                    {{ i.row.createEmpType + '-' + i.row.createEmp }}
                  </template>
                </el-table-column>
                <el-table-column show-overflow-tooltip prop="event" label="操作事件" width="240" />
                <el-table-column show-overflow-tooltip prop="content" label="备注" width="220" />
                <el-table-column prop="createTime" label="时间" width="120" />
              </el-table>
            </div>
            <div class="pagination">
              <Pagination
                ref="pagination"
                :list_total="totalList"
                @size-change="getOrderFeeLogListData()"
                @current-change="getOrderFeeLogListData()"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <template #footer>
      <h-button is-modal @click="onClose">关闭</h-button>
    </template>
  </h-drawer>
</template>

<script lang="ts" setup>
  import { ref, toRefs, watch } from 'vue'
  import { getOrderFeeDetail, getOrderFeeLogList, OrderFeeDetailProjectInfo } from '@/api/order'
  import Pagination from '@/components/Pagination/index.vue'
  import { ElMessage, TabPaneName } from 'element-plus'
  import { ServiceFeeDetail, ServiceFeeDetailProject } from './types'

  const props = defineProps({
    modelValue: Boolean,
    feeId: {
      type: String,
      default: () => '',
    },
    workNo: String,
    feeNo: String,
  })

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'update-list'): void
  }>()

  // 附件列宽
  const annexColumnWidth = ref(70)

  // 设置附件列的宽度
  const setAnnexColumnWidth = () => {
    let maxImageLength = Math.max(...feeDetails.value.map((item) => item.images.length))

    // 这是为了解决只有一张图时，列宽会变得很小，导致标题会换行
    if (maxImageLength > 0) {
      annexColumnWidth.value = maxImageLength * 60 + (maxImageLength - 1) * 8 + 24
    }
  }

  const { feeId } = toRefs(props)
  const loading = ref(false)

  // 服务费用详情
  const detailData = ref<ServiceFeeDetail | null>(null)
  const detailDataLog = ref(null)
  const activeName = ref('first')

  // 服务费用项目
  const feeDetails = ref<Array<ServiceFeeDetailProject>>([])

  const totalList = ref(0)

  // 操作日志分页组件实例
  const pagination = ref<InstanceType<typeof Pagination> | null>(null)

  const options = [
    { value: 1, name: '待审核' },
    { value: 2, name: '已通过' },
    { value: 3, name: '已驳回' },
  ]

  /**
   * 根据服务项目ID获取服务项目详情
   * @param {string} id 服务项目ID
   */
  const getOrderFeeDetailProjectInfo = async (id: string) => {
    loading.value = true
    const res = await getOrderFeeDetail(id)
    if (res.data.success) {
      detailData.value = res.data.data.row
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        duration: 5000,
        plain: true,
        type: 'error',
      })
    }
    loading.value = false
  }

  /**
   * 获取操作日志详情
   */
  const getOrderFeeLogListData = async () => {
    loading.value = true
    let data = {
      limit: 50,
      page: 1,
    }
    if (pagination.value) {
      data.limit = pagination.value.size
      data.page = pagination.value.current
    }
    const res = await getOrderFeeLogList(data, feeId.value)
    if (res.data.success) {
      detailDataLog.value = res.data.data.rows
      totalList.value = Number(res.data.data.total)
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        duration: 5000,
        plain: true,
        type: 'error',
      })
    }
    loading.value = false
  }

  // 根据服务项目ID获取项目信息列表加载
  const getOrderFeeDetailProjectLoading = ref(false)

  /**
   * 根据服务项目ID获取项目信息列表
   * @param {string} id 服务项目ID
   */
  const getOrderFeeDetailProject = async (id: string) => {
    getOrderFeeDetailProjectLoading.value = true
    const res = await OrderFeeDetailProjectInfo(id)
    getOrderFeeDetailProjectLoading.value = false
    if (res.data.success) {
      feeDetails.value = res.data.data.row
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        duration: 5000,
        plain: true,
        type: 'error',
      })
    }
  }

  /**
   * tab标签改变事件
   * @param {string} val 标签名
   */
  const handleClick = (val: TabPaneName) => {
    switch (val) {
      case 'first':
        getOrderFeeDetailProject(feeId.value)
        break
      case 'second':
        break
      case 'third':
        getOrderFeeLogListData()
        break
    }
  }

  const visible = ref(false)
  const onClose = () => {
    visible.value = false
    activeName.value = 'first'
    emits('update:modelValue', visible.value)
  }

  watch(
    props,
    async (value) => {
      visible.value = value.modelValue
      if (visible.value && value.feeId) {
        await getOrderFeeDetailProjectInfo(value.feeId)
        await getOrderFeeDetailProject(value.feeId)
        setAnnexColumnWidth()
      }
    },
    { immediate: true, deep: true },
  )
</script>

<style lang="scss" scoped>
  .detail_info_container {
    display: flex;
    flex-direction: column;
    row-gap: 12px;

    .title {
      padding-left: 6px;
      border-left: 3px solid $primaryColor;
      font-size: 14px;
      font-weight: bold;
    }

    .detail_info {
      display: flex;
      flex-direction: column;
      row-gap: 12px;
      padding: 0 24px 20px 24px;

      .info_item_container {
        display: flex;
        column-gap: 106px;
        row-gap: 12px;
        flex-wrap: wrap;

        .info_item {
          display: flex;
          gap: 5px;
          min-width: 200px;
          align-items: center;

          .label {
            color: #606266;
          }
        }
      }
    }
  }

  .body {
    height: calc(100% - 123px);

    :deep(.el-tabs) {
      height: 100%;

      .el-tabs__header {
        margin: 0;
        padding-bottom: 12px;
      }

      .el-tabs__content {
        height: calc(100% - 52px);

        .el-tab-pane {
          height: 100%;

          .fee_project {
            max-height: 100%;
          }

          .operate_log_container {
            height: 100%;

            .table {
              max-height: calc(100% - 40px);
            }

            .pagination {
              height: 28px;
              padding-top: 12px;
            }
          }
        }
      }
    }
  }
  .footer_btn {
    display: flex;
    justify-content: end;
    align-items: center;
    margin-right: 8px;
  }

  .disf_ipc {
    display: flex;

    p {
      width: 40px;
      height: 40px;
      margin-right: 6px;
      border: 1px solid #7f7f7f27;
      border-radius: 2px;
      box-sizing: border-box;

      .img {
        width: 100%;
        border-radius: 2px;
        cursor: pointer;
      }
    }
  }

  .coloe {
    margin-top: 10px;
    text-align: right;
  }

  .pagination {
    height: 42px;
    display: flex;
    justify-content: flex-end;
  }
</style>
